﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.hqApplication.Command.Fieldses
{
    public class SearchFieldsHandler : IRequestHandler<SearchFieldsCommand, Result<List<Fields>>>
    {
        /// <summary>
        /// 栏位表
        /// </summary>
        private readonly IBaseRepository<Fields> _fieldRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchFieldsHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="fieldRepository"></param>
        /// <param name="logger"></param>
        public SearchFieldsHandler(IBaseRepository<Fields> fieldRepository, ILogger<SearchFieldsHandler> logger)
        {
            _fieldRepository = fieldRepository;
            _logger = logger;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<List<Fields>>> Handle(SearchFieldsCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<List<Fields>>() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = await (await _fieldRepository.GetAll()).Where(x => x.BedroomId == request.BedroomId).ToListAsync();
                if (query.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "根据栋舍ID获取栏位成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "根据栋舍ID获取栏位异常" + ex.Message;
                _logger.LogError("根据栋舍ID获取栏位异常" + ex.Message);
            }
            return result;
        }
    }
}
